package ch.vd.dec.selt.petale

class TypologieEmolument{
	
	BaseLegale base
	TypeAutorisation aut
	Categorie cat
	SousCategorie subcat
	Prestation pre
	Float emo
	Float emo_saiso
	Integer priorite = 32
	String uniqueKey
	
	def TypologieAutorisation
	
	static belongsTo = [base:BaseLegale, aut:TypeAutorisation, cat:Categorie, pre:Prestation]
	
	static mapping = {
		table 'TEMO_TYPO_FAC'
		base column:'BL'
		aut column:'TY_AUT'
		cat column:'CAT'
		subcat column:'SUBCAT'
		pre column:'PRE'
		emo column:'EMO'
		emo_saiso column:'EMO_SAISO'
		priorite column:'PRIORITY'
		uniqueKey column:'UNIQUEKEYSHARP'
		id generator:'sequence', params:[sequence: 'TEMO_TYPO_FAC_SEQ']
		version true
	}
	
	static constraints = {
		base(nullable: true, unique:['aut', 'cat', 'subcat', 'pre'], validator: {val, obj -> 
			def entries = TypologieAutorisation.createCriteria().list {
				obj.base != null ? eq('base', obj.base) : true
				obj.aut != null ? eq('aut', obj.aut) : true
				obj.cat != null ? eq('cat', obj.cat) : true
			}
			val in [*entries.base,null]
		})
		aut(nullable:true, validator: {val, obj -> 
			def entries = TypologieAutorisation.createCriteria().list {
				obj.base != null ? eq('base', obj.base) : true
				obj.aut != null ? eq('aut', obj.aut) : true
				obj.cat != null ? eq('cat', obj.cat) : true
			}
			val in [*entries.aut,null]
		})
		cat(nullable:true, validator: {val, obj -> 
			def entries = TypologieAutorisation.createCriteria().list {
				obj.base != null ? eq('base', obj.base) : true
				obj.aut != null ? eq('aut', obj.aut) : true
				obj.cat != null ? eq('cat', obj.cat) : true
			}
			val in [*entries.cat,null]
		})
		subcat(nullable:true, validator: {val, obj -> 
			def entries = TypologieAutorisation.createCriteria().list {
				obj.base != null ? eq('base', obj.base) : true
				obj.aut != null ? eq('aut', obj.aut) : true
				obj.cat != null ? eq('cat', obj.cat) : true
			}
			val in [*entries.subcat,null]
		})
		pre(nullable:true, validator: {val, obj -> 
			def entries = TypologieAutorisation.createCriteria().list {
				obj.base != null ? eq('base', obj.base) : true
				obj.aut != null ? eq('aut', obj.aut) : true
				obj.cat != null ? eq('cat', obj.cat) : true
			}
			val in [*entries.pre,null]
		})
		emo(nullable:false)
		emo_saiso(nullable:false)
		priorite(blank: false, range:1..32)
		uniqueKey(blank: false, maxSize:30, unique:true)
    }
	
	def definePriorite = {
		priorite = 32  - (base != null ?1:0) - (aut != null ?2:0) - (cat != null ?4:0) - (subcat != null ?8:0) - (pre != null ?16:0)
	}

	def defineUniqueKey = {
		uniqueKey = (base != null ?base.id:0) + '#' + (aut != null ?aut.id:0) + '#' + (cat != null ?cat.id:0) + '#' + (subcat != null ?subcat.id:0) + '#' + (pre != null ?pre.id:0)
	}
	
	def beforeInsert = {
		definePriorite()
		defineUniqueKey()
	}
	
	def beforeUpdate = {
		definePriorite()
		defineUniqueKey()
	}
	
}